package com.zhilifang.modules.zlf.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zhilifang.modules.zlf.entity.ImgUpload;
import com.zhilifang.modules.zlf.utils.Utils;

/**
 * Controller 后台首页>>发布产品Controller
 */
@Controller
@RequestMapping("/productController")
public class ProductController {


	/**
	 * 接收图片上传
	 * 
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value = "/imgUpload", method = RequestMethod.POST)
	@ResponseBody
	public ImgUpload imgUpload(@RequestParam("img") MultipartFile list , String type) throws IllegalStateException, IOException{
		ImgUpload result = new ImgUpload();
		String[] data = new String[5];
		if(type==""||type==null){
			type ="product";
		}
		String path = Utils.isLinux(type);  		//判断当前系统类型，根据系统类型存放文件
		//创建图片文件夹存放图片
        File fileDir = new File(path);
        //判断文件夹是否存在
        if(!fileDir.exists()){
            //不存在的话,创建文件夹
            fileDir.mkdirs();
        }
        String fileName = returnPrefixSuffixName(list.getOriginalFilename());
        fileDir = new File(path+fileName);
        list.transferTo(fileDir);//实现文件的上传
		data[0]="/localImg/"+type+"/"+fileName;
        result.setErrno("0");
        result.setData(data);
		return result;
	}
	
	/**
	 * 随机生成文件名称
	 * 名称当前时间+随机数+文件后缀名
	 * 
	 */
	public String returnPrefixSuffixName(String fileName) {
		long time = new Date().getTime() + Math.round(Math.random() * 1000);  //生成随机数
        String prefix = time + "";  //类型转换
		String[] strArray = fileName.split("\\.");
        int suffixIndex = strArray.length -1;
		String suffix =  "."+strArray[suffixIndex];  //生成文件后缀名
		return prefix+suffix;
	}
	
	/** 
	* 判断是linux系统还是其他系统 
	* 如果是Linux系统，返回true，否则返回false 
	*/ 
	public static boolean isLinux() { 
		return System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0; 
	}
	
	
	
}
